const cloud = require('@cloudbase/node-sdk')

// 初始化云开发实例
const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV
})

// 获取数据库引用
const db = app.database()
const collection = db.collection('bubble_tags')

/**
 * bubble_tags CRUD 云函数
 * @param {Object} event - 云函数参数
 * @param {Object} context - 云函数上下文
 */
exports.main = async (event, context) => {
    const { action, data } = event

    try {
        // 操作日志
        console.log('bubble-tags-crud 调用:', { action, data })

        switch (action) {
            case 'create':
                return await createBubbleTag(data)
            case 'read':
                return await getBubbleTag(data)
            case 'update':
                return await updateBubbleTag(data)
            case 'delete':
                return await deleteBubbleTag(data)
            case 'list':
                return await listBubbleTags(data)
            default:
                throw new Error('无效的操作类型')
        }
    } catch (error) {
        console.error('bubble-tags-crud 错误:', error)
        return {
            code: -1,
            message: error.message,
            data: null
        }
    }
}

// 创建气泡标签
async function createBubbleTag(data) {
    const {
        tag,
        mapNode,
        type,
        size,
        position,
        animationDuration,
        gradient,
        enable
    } = data

    if (!tag || !mapNode || !type) {
        throw new Error('标签、节点名称和类型为必填项')
    }

    // 生成唯一ID
    const id = `bubble_${Date.now()}_${Math.floor(Math.random() * 1000)}`

    const result = await collection.add({
        id,
        tag,
        mapNode,
        type,
        size: size || 100,
        position: position || { x: 500, y: 500 },
        animationDuration: animationDuration || 2.0,
        gradient: gradient || { start: '#1089ff', end: '#00bcd4' },
        enable: enable !== false, // 默认为true
        createdAt: new Date(),
        updatedAt: new Date()
    })

    return {
        code: 0,
        message: '创建成功',
        data: result
    }
}

// 获取单个气泡标签
async function getBubbleTag(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).get()

    if (!result.data || result.data.length === 0) {
        throw new Error('气泡标签不存在')
    }

    return {
        code: 0,
        message: '查询成功',
        data: result.data[0]
    }
}

// 更新气泡标签
async function updateBubbleTag(data) {
    const {
        _id,
        tag,
        mapNode,
        type,
        size,
        position,
        animationDuration,
        gradient,
        enable
    } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const updateData = {
        updatedAt: new Date()
    }

    if (tag !== undefined) updateData.tag = tag
    if (mapNode !== undefined) updateData.mapNode = mapNode
    if (type !== undefined) updateData.type = type
    if (size !== undefined) updateData.size = size
    if (position !== undefined) updateData.position = position
    if (animationDuration !== undefined) updateData.animationDuration = animationDuration
    if (gradient !== undefined) updateData.gradient = gradient
    if (enable !== undefined) updateData.enable = enable

    const result = await collection.doc(_id).update(updateData)

    return {
        code: 0,
        message: '更新成功',
        data: result
    }
}

// 删除气泡标签
async function deleteBubbleTag(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('ID为必填项')
    }

    const result = await collection.doc(_id).remove()

    return {
        code: 0,
        message: '删除成功',
        data: result
    }
}

// 获取气泡标签列表
async function listBubbleTags(data) {
    const { page = 1, pageSize = 10, id, tag, mapNode, type, enable } = data

    // 构建查询条件
    let queryCondition = {}

    if (id) {
        queryCondition.id = db.RegExp({
            regexp: id,
            options: 'i',
        })
    }

    if (tag) {
        queryCondition.tag = db.RegExp({
            regexp: tag,
            options: 'i',
        })
    }

    if (mapNode) {
        queryCondition.mapNode = db.RegExp({
            regexp: mapNode,
            options: 'i',
        })
    }

    if (type) {
        queryCondition.type = db.RegExp({
            regexp: type,
            options: 'i',
        })
    }

    // 根据启用状态筛选
    if (enable !== undefined) {
        const cmd = db.command
        if (enable === true) {
            // 构建启用状态的查询条件：enable为true或字段不存在
            queryCondition = cmd.and([
                queryCondition,
                cmd.or([
                    { enable: true },
                    { enable: cmd.exists(false) }
                ])
            ])
        } else if (enable === false) {
            // 禁用状态：enable必须为false
            queryCondition.enable = false
        }
    }

    console.log('查询条件:', JSON.stringify(queryCondition))

    // 创建查询对象
    const dbQuery = collection.where(queryCondition)

    const result = await dbQuery
        .orderBy('createdAt', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    const countResult = await dbQuery.count()

    return {
        code: 0,
        message: '查询成功',
        data: {
            list: result.data,
            total: countResult.total,
            page,
            pageSize
        }
    }
}